package com.sd.activity;

import java.net.URLEncoder;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.sd.util.HttpUtil;
import com.sd.util.StringUtils;
import com.snda.woa.android.OpenAPI;
import com.snda.woa.android.callback.MobileLoginCallBack;

/**
 * 
 * 本机号码登录
 * 
 * @author david
 */
public class MobileReginWithSVR extends BaseActivity implements Button.OnClickListener, MobileLoginCallBack {
	private static final String tag = MobileReginWithSVR.class.getSimpleName();

	private String oriSessionId;
	private boolean isChecked = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(tag, "MobileReginWithSVR onCreate start ...");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mobile_regin_svr_ui);

		log_textView = (TextView) findViewById(R.id.log_textView);
		log_textView.setMovementMethod(ScrollingMovementMethod.getInstance());
		clearLog_btn = (Button) findViewById(R.id.clearlog_btn);
		clearLog_btn.setOnClickListener(this);
		refresh_btn = (Button) findViewById(R.id.refresh_btn);
		refresh_btn.setOnClickListener(this);

		processRegin();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.clearlog_btn:
			log = new StringBuffer("");
			log_textView.setText(log.toString());
			break;
		case R.id.refresh_btn:
			processRegin();
			break;
		default:
			break;
		}
	}

	@Override
	public void callBack(int code, String message, String sessionId) {
		Log.d(tag, "MobileReginWithSVR doCallBack start ...");
		printLogOnScreen("sessionId: " + sessionId + " \n");
		printLogOnScreen("call back status: " + OpenAPI.getStatusText(code) + " \n");

		// sessionId由sdk回调返回
		if (StringUtils.checkCallBackStat(code, sessionId)) {
			oriSessionId = sessionId;

			// 通过应用自身服务端与woa服务端进行sessionId验证（此步骤是判断登录成功与否的关键）
			String result = HttpUtil.readStringFromUrl(BaseActivity.appId, sessionId, "utf-8", new Object());
			printLogOnScreen("result: " + result + " \n");
			Log.d(tag, "result: " + result + " \n");
			if (!StringUtils.isEmpty(result)) {
				EBookActivity.user = StringUtils.getValueByKey(result, "sid");
				token = StringUtils.getValueByKey(result, "token");
				resultCode = StringUtils.getValueByKey(result, "resultCode");
				// 如果报“未收到客户端短信”的错误码，复杂流程下需要客户端进行到appserver进行状态轮询
				if (token == null && "-10256304".equals(resultCode)) {
					// 判断流程模式（简单流程：0   复杂流程：1）
					// 复杂流程需要进行状态轮询
					printLogOnScreen("检测服务端是否已经收到发送的短信中，请稍后... \n");
					// 进行后台状态检查，此处的代码实现方法仅供参考
					checkState();
				}
				if (!StringUtils.isEmpty(token) && "0".equals(resultCode)) {
					// 验证完sessionId后不管成功与否，都需要反馈给sdk
					// 调用反馈接口（接口参数：应用上下文，是否登录成功，sessionId验证返回的结果码，验证获取的token）
					// sessionId验证成功即可认为是此次登录成功
					OpenAPI.loginFeedBack(MobileReginWithSVR.this, true, resultCode!=null?Integer.valueOf(resultCode):-1, token);
				} else {
					// sessionId验证失败“是否登录成功”请使用false
					OpenAPI.loginFeedBack(MobileReginWithSVR.this, false, resultCode!=null?Integer.valueOf(resultCode):-1, token);
				}
			} else {
				// sessionId验证返回的状态码没有请使用-1代替
				OpenAPI.loginFeedBack(MobileReginWithSVR.this, false, -1, token);
				printLogOnScreen("validate session id has some problem \n");
			}

			if (isChecked && !StringUtils.isEmpty(token)) {
				printLogOnScreen("token: " + token + " \n");
				Log.d(tag, "token: " + token + " \n");
				printLogOnScreen("OpenAPI.loginFeedBack \n");
				printLogOnScreen("恭喜你已经登录成功 \n");
			}

		} else {
			// sdk逻辑处理出现异常
			Log.d(tag, "sessionId has some problem \n");
			printLogOnScreen("sessionId has some problem \n");
		}
		duration = (System.currentTimeMillis() - startTime);
		printLogOnScreen("duration:----------------" + duration + "ms---------\n\n");
	}

	// ---------------- customize method ----------------
	/**
	 * 业务逻辑处理
	 */
	private void processRegin() {
		Log.d(tag, "MobileReginWithSVR processRegin start ...");
		startTime = System.currentTimeMillis();

		printLogOnScreen("SDK version is 3.3 \n");

		// 调用本机号登录接口（接口参数：本机号登录回调类，应用上下文，扩展参数）
		OpenAPI.mobileLogin(this, true, MobileReginWithSVR.this, null);
		printLogOnScreen("OpenAPI.mobileLogin \n");
	}

	/**
	 * 复杂流程下检查appserver缓存的”客户端短信是否已经发送到woaserver“的状态
	 * 如果woaserver收到客户端的上行短信会回调appserver的回调接口
	 * 以便告知appserver其客户端发送的上行短信已经被收到
	 */
	public void checkState() {
		Log.d(tag, "MobileReginWithSVR checkState start ...");
		printLogOnScreen("checkState start ... \n");
		long startTime = System.currentTimeMillis();
		long endTime = 0l;
		if (StringUtils.isEmpty(appserverPath)) {
			appserverPath = "http://10.132.17.92:8080/appdemo/callBackServlet?checkState=1&oriSessionId=";
		}
		
		// 检查appserver的缓存
		String url = appserverPath + "callBackServlet?checkState=1&oriSessionId=" + URLEncoder.encode(oriSessionId);
		printLogOnScreen("checkState request url is: \n" + url + " \n");
		while (true) {
			String result = HttpUtil.readStringFromUrl(url, "utf-8", 3000, new Object());
			if (result != null && !"ERROR".equals(result)) {
				token = result;
				break;
			}
			endTime = System.currentTimeMillis();
			
			if ((endTime - startTime) >= 20000) {
				Log.w(tag, "time out to check state");
				printLogOnScreen("CheckStateTask timeout ... \n");
				isChecked = false;
				break;
			}
		}
	}

}
